const path = require('path')
const fs = require('fs')
const Database = require('./database')

/**
 * 扫指定目录并读取文件内容
 * @param {*} dir 目录
 * @param {*} cb 回调
 * @param {*} env 环境
 */
function scanFilesByFolder(dir, cb, env = 'development') {
  let _folder = path.resolve(__dirname, dir)
  if (!hasFolder(_folder)) return
  try {
    const files = fs.readdirSync(_folder)
    files.forEach(file => {
      const [name, type] = file.split('.')
      switch (type) {
        case 'js':
          cb && cb(name, require(_folder + '/' + name))
          break
        case 'json':
          cb && cb(name, require(_folder + '/' + file)[env])
          break
        default:
      }
    })
  } catch (error) {
    console.log('文件自动加载失败...', error)
  }
}

/**
 * 检测文件夹是否存在
 * @param {*} path 文件夹路径
 * @returns Boolean
 */
function hasFolder(path) {
  try {
    fs.statSync(path)
    return true
  } catch (err) {
    return false
  }
}

module.exports = app => {
  // config
  app.$config = {}
  scanFilesByFolder(
    './config',
    (key, value) => {
      app.$config[key] = value
    },
    app.env
  )

  // database
  app.$database = Database(app)

  // services
  app.$services = {}
  scanFilesByFolder('./services', (key, value) => {
    app.$services[key] = value(app)
  })

  // controllers
  app.$controllers = {}
  scanFilesByFolder('./controllers', (key, value) => {
    app.$controllers[key] = value({ ...app })
  })

  // routes
  scanFilesByFolder('./routes', (key, value) => {
    const router = require('koa-router')()
    const route = value({ ...app, router })
    app.use(route.routes(), route.allowedMethods())
  })
}
